import { defineStore } from 'pinia'

export const useOrderStore = defineStore('order', {
  state: () => ({
    tableNumber: '',
    peopleCount: 1,
    menuItems: [
      { id: 1, name: '宫保鸡丁', price: 28, category: '热菜', image: '' },
      { id: 2, name: '麻婆豆腐', price: 18, category: '热菜', image: '' },
      { id: 3, name: '鱼香肉丝', price: 26, category: '热菜', image: '' },
      { id: 4, name: '红烧肉', price: 32, category: '热菜', image: '' },
      { id: 5, name: '清炒时蔬', price: 12, category: '素菜', image: '' },
      { id: 6, name: '酸辣汤', price: 10, category: '汤类', image: '' },
      { id: 7, name: '扬州炒饭', price: 15, category: '主食', image: '' },
      { id: 8, name: '凉拌黄瓜', price: 8, category: '凉菜', image: '' }
    ],
    categories: ['热菜', '素菜', '汤类', '主食', '凉菜'],
    selectedCategory: '热菜',
    cart: [],
    deliveryMethod: 'collection', // deliver 或 collection
    paymentMethod: 'online', // online 或 on_delivery
    orders: [
      { id: '001', items: ['宫保鸡丁', '酸辣汤'], status: '配送中', total: 38 },
      { id: '002', items: ['麻婆豆腐', '扬州炒饭'], status: '准备中', total: 33 },
      { id: '003', items: ['红烧肉', '清炒时蔬'], status: '已完成', total: 44 }
    ]
  }),
  
  getters: {
    cartTotal: (state) => {
      return state.cart.reduce((total, item) => total + (item.price * item.quantity), 0)
    },
    cartItemCount: (state) => {
      return state.cart.reduce((count, item) => count + item.quantity, 0)
    }
  },
  
  actions: {
    setTableNumber(number) {
      this.tableNumber = number
    },
    
    setPeopleCount(count) {
      this.peopleCount = count
    },
    
    selectCategory(category) {
      this.selectedCategory = category
    },
    
    addToCart(item) {
      const existingItem = this.cart.find(cartItem => cartItem.id === item.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        this.cart.push({ ...item, quantity: 1 })
      }
    },
    
    removeFromCart(itemId) {
      const index = this.cart.findIndex(item => item.id === itemId)
      if (index !== -1) {
        this.cart.splice(index, 1)
      }
    },
    
    updateCartItemQuantity(itemId, quantity) {
      const item = this.cart.find(cartItem => cartItem.id === itemId)
      if (item) {
        item.quantity = quantity
        if (item.quantity <= 0) {
          this.removeFromCart(itemId)
        }
      }
    },
    
    setDeliveryMethod(method) {
      this.deliveryMethod = method
    },
    
    setPaymentMethod(method) {
      this.paymentMethod = method
    },
    
    clearCart() {
      this.cart = []
    },
    
    addOrder(order) {
      this.orders.unshift(order)
    }
  }
})